<?php
namespace app\spadmin\controller;

use app\common\controller\Backend;
use think\Controller;
use think\Config;
use think\Validate;
use think\captcha\Captcha;
use think\Cache;
use think\Session;
use think\Cookie;
use think\Db;

class Index extends Backend
{
    public function _initialize()
    {
        parent::_initialize();        
    }
    //首页
    public function index()
    {
        return $this->fetch();
    }
    //默认页
    public function dashed(){
        
        return $this->fetch();
    }
    public function menu(){
        if($this->request->isAjax()){
            $menu = $this->auth->getMenu();
            foreach ($menu as $key => $value) {
                if($value['type'] != 0){
                    $menu[$key]['href'] = url($value['url']);
                }else{
                    $menu[$key]['href'] = '';
                }
            }
            $this->success('',null,listToTree($menu));
        }
    }

    public function recache(){
        rmdirs(CACHE_PATH, false);
        Cache::clear();
        $this->success('清除缓存成功');
    }

    public function login()
    {
        
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                'captcha' => 'require|captcha',
            ];
            $validate = new Validate($rule, [], ['username' => '账户', 'password' => '密码', 'captcha' => '验证码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }
            $result = $this->auth->login($data['username'], $data['password'], $data['keeplogin'] ? 86400*30 : 0);
            if ($result === true) {
                $this->success('登录成功');
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : '账户或者密码错误';
                $this->error($msg);
            }
        }
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect('index/index');
        }
        return $this->fetch();
    }

    public function logout()
    {
        if($this->request->isPost()){
            Session::delete("spadmin_admin");
            Cookie::delete("spadmin_keeplogin");
            $this->success('退出成功');
        }
    }

    public function captcha() {
        $captcha = new Captcha();
        $captcha->useArithmetic = true;
        return $captcha->entry();
    }
}